﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using YaAppoint.Rules;

namespace YaAppoint.LocalCache
{
    public static class LocalCache
    {
        // 静态字典存储所有 RuleFilter 缓存
        private static readonly ConcurrentDictionary<Guid, CacheItem<RuleFilter>> _ruleFilters =
            new ConcurrentDictionary<Guid, CacheItem<RuleFilter>>();

       

        // 定时清理任务
        private static readonly Timer _cleanupTimer;
        

        static LocalCache()
        {
            
        }

        /// <summary>
        /// 获取Guid对应的 RuleFilter
        /// </summary>
        public static RuleFilter Get(Guid key)
        {
            if (_ruleFilters.TryGetValue(key, out var cacheItem))
            {
                if (!cacheItem.IsExpired)
                {
                    return cacheItem.Value;
                }
                else
                {
                    // 已过期
                    _ruleFilters.TryRemove(key,out _);
                }
            }
            return null;
        }

        /// <summary>
        /// 设置缓存
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="expiration"></param>
        public static void Set(Guid key, RuleFilter value, TimeSpan? expiration = null)
        {
            var cacheItem = new CacheItem<RuleFilter>(value, expiration);
            _ruleFilters.AddOrUpdate(key, cacheItem, (k, existing) => cacheItem);
        }

        /// <summary>
        /// 移除指定缓存
        /// </summary>
        public static bool Remove(Guid key)
        {
            return _ruleFilters.TryRemove(key, out _);
        }

        /// <summary>
        /// 检查缓存是否存在且未过期
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool Contains(Guid key)
        {
            if (_ruleFilters.TryGetValue(key, out var cacheItem))
            {
                if (!cacheItem.IsExpired)
                {
                    return true;
                }
                else
                {
                    _ruleFilters.TryRemove(key, out _);
                }
            }
            return false;
        }

        /// <summary>
        /// 获取所有缓存健（不能包含已过期的）
        /// </summary>
        /// <returns></returns>
        public static List<Guid> GetAllKeys()
        {
            CleanUpExpiredItems();// 先清理过期项
            return _ruleFilters.Keys.ToList();
        }

        /// <summary>
        /// 清理所有缓存
        /// </summary>
        public static void Clear()
        {
            _ruleFilters.Clear();
        }

        /// <summary>
        /// 获取缓存统计信息
        /// </summary>
        /// <returns></returns>
        public static (int TotalCount, int ExpiredCount) GetStatistics()
        {
            var totalCount = _ruleFilters.Count;
            var expiredCount = _ruleFilters.Count(pair => pair.Value.IsExpired);
            return (totalCount, expiredCount);
        }

        /// <summary>
        /// 清理过期项目
        /// </summary>
        /// <param name="state"></param>
        private static void CleanUpExpiredItems(object state = null)
        {
            // 获取过期的Key集合
            var expiredKeys = _ruleFilters.Where(pair => pair.Value.IsExpired)
                                          .Select(pair => pair.Key)
                                          .ToList();

            foreach (var key in expiredKeys)
            {
                _ruleFilters.TryRemove(key, out _);
            }
        }
    }
}
